export default {
	// 开启命名空间
	namespaced:true,
	state:() => ({
		// 购物车数据
		// 默认有goods_id,goods_name,goods_state,goods_count,goods_price,goods_small_log
		cart:JSON.parse(uni.getStorageSync('cart') || '[]')
	}),
	mutations:{
		addCart(state,goods){
			const findResult = state.cart.find(item=> item.goods_id === goods.goods_id)
			if(!findResult){
				state.cart.push(goods)
			}else{
				findResult.goods_count++
			}
			this.commit('m_cart/saveStorage')
		},
		// 将购物车数据持久化存储到本地
		saveStorage(state){
			uni.setStorageSync('cart',JSON.stringify(state.cart))
		},
		// 勾选商品复选框状态
		setRadioChange(state,goods){
			const findResult = state.cart.find(item => item.goods_id === goods.goods_id)
			if(findResult) {
				findResult.goods_state = goods.goods_state
				this.commit('m_cart/saveStorage')
			}
		},
		// 修改购物车里goods_count的值
		setNumChange(state,goods) {
			const findResult = state.cart.find(item => item.goods_id === goods.goods_id)
			if(findResult) {
				findResult.goods_count = goods.goods_count
				this.commit('m_cart/saveStorage')
			}
		},
		// 删除某件商品
		removeGoods(state,goods){
			state.cart = state.cart.filter(item => item.goods_id !== goods.goods_id)
			this.commit('m_cart/saveStorage')
		},
		// 修改商品全选反选的状态
		setGoodsState(state,newState) {
			state.cart.forEach(item => item.goods_state = newState)
			this.commit('m_cart/saveStorage')
		}
	},
	getters:{
		// 动态统计商品购物车的总数量
		total(state) {
			// let c = 0
			// state.cart.forEach(goods => c += goods.goods_count)
			// return c
		 return	state.cart.reduce((total,item) => total += item.goods_count, 0 )
		},
		// 动态统计购物车商品总数量
		checkCart(state) {
			return state.cart.filter(item => item.goods_state).reduce((total,item) => total += item.goods_count ,0)
		},
		// 动态渲染购物车商品的总价格
		totalPrice(state) {
			return state.cart.filter(item => item.goods_state)
			      .reduce((total,item) => total += item.goods_count * item.goods_price ,0 )
			      .toFixed(2)
		}
	}
}